package com.dempsey.common.cos.service;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.Bucket;
import com.qcloud.cos.model.COSObjectSummary;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.ListObjectsRequest;
import com.qcloud.cos.model.ObjectListing;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.StorageClass;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Date;
import java.util.List;

/**
 * @author Dempsey
 * Date 2022/5/20
 * Description
 */

@Component
public class CosImageService {

    private static final String BUCKET_NAME = "dempsey-seckill-1300280569";
    private static final String PATH_PREFIX = "https://dempsey-seckill-1300280569.cos.ap-shanghai.myqcloud.com/";

    @Autowired
    private COSClient cosClient;

    /**
     * 上传文件
     *
     * @return //绝对路径和相对路径都OK
     */
    public String uploadFile(File file, String fileName) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, fileName, file);

        // 设置存储类型, 默认是标准(Standard), 低频(standard_ia),一般为标准的
        putObjectRequest.setStorageClass(StorageClass.Standard);

        try {
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        } catch (CosClientException e) {
            throw new CosClientException("文件上传失败");
        }

        return PATH_PREFIX + fileName;
    }

    /**
     * 下载文件
     *
     * @param bucketName
     * @param key
     * @return
     */
    public String downLoadFile(String bucketName, String key) {
        File downFile = new File("E:\\software\\1.jpg");
        GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);

        ObjectMetadata downObjectMeta = cosClient.getObject(getObjectRequest, downFile);

        return downObjectMeta.getETag();
    }

    /**
     * 删除文件
     *
     * @param bucketName
     * @param key
     */
    public void deleteFile(String bucketName, String key) {
        try {
            cosClient.deleteObject(bucketName, key);
        } catch (CosClientException e) {
            e.printStackTrace();
        }

    }

    /**
     * 创建桶
     *
     * @param bucketName
     * @return
     * @throws CosClientException
     * @throws CosServiceException
     */
    public Bucket createBucket(String bucketName) throws CosClientException, CosServiceException {
        Bucket bucket = null;
        try {
            bucket = cosClient.createBucket(bucketName);
        } catch (CosClientException e) {
            e.printStackTrace();
        }
        return bucket;
    }

    ;

    /**
     * 删除桶
     *
     * @param bucketName
     * @throws CosClientException
     * @throws CosServiceException
     */
    public void deleteBucket(String bucketName) throws CosClientException, CosServiceException {
        try {
            cosClient.deleteBucket(bucketName);
        } catch (CosClientException e) {
            e.printStackTrace();
        } finally {
        }
    }

    /**
     * 判断桶是否存在
     *
     * @param bucketName
     * @return
     * @throws CosClientException
     * @throws CosServiceException
     */
    public boolean doesBucketExist(String bucketName) throws CosClientException, CosServiceException {
        return cosClient.doesBucketExist(bucketName);
    }


    /**
     * 查看桶文件
     *
     * @param bucketName
     * @return
     * @throws CosClientException
     * @throws CosServiceException
     */
    public ObjectListing listObjects(String bucketName) throws CosClientException, CosServiceException {
        // 获取 bucket 下成员（设置 delimiter）
        ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
        listObjectsRequest.setBucketName(bucketName);
        // 设置 list 的 prefix, 表示 list 出来的文件 key 都是以这个 prefix 开始
        listObjectsRequest.setPrefix("");
        // 设置 delimiter 为/, 即获取的是直接成员，不包含目录下的递归子成员
        listObjectsRequest.setDelimiter("/");
        // 设置 marker, (marker 由上一次 list 获取到, 或者第一次 list marker 为空)
        listObjectsRequest.setMarker("");
        // 设置最多 list 100 个成员,（如果不设置, 默认为 1000 个，最大允许一次 list 1000 个 key）
        listObjectsRequest.setMaxKeys(100);

        ObjectListing objectListing = cosClient.listObjects(listObjectsRequest);
        // 获取下次 list 的 marker
        String nextMarker = objectListing.getNextMarker();
        // 判断是否已经 list 完, 如果 list 结束, 则 isTruncated 为 false, 否则为 true
        boolean isTruncated = objectListing.isTruncated();
        List<COSObjectSummary> objectSummaries = objectListing.getObjectSummaries();
        for (COSObjectSummary cosObjectSummary : objectSummaries) {
            // get file path
            String key = cosObjectSummary.getKey();
            // get file length
            long fileSize = cosObjectSummary.getSize();
            // get file etag
            String eTag = cosObjectSummary.getETag();
            // get last modify time
            Date lastModified = cosObjectSummary.getLastModified();
            // get file save type
            String storageClassStr = cosObjectSummary.getStorageClass();
        }
        return objectListing;
    }

    /**
     * 查询一个 Bucket 所在的 Region。
     *
     * @param bucketName
     * @return
     * @throws CosClientException
     * @throws CosServiceException
     */
    public String getBucketLocation(String bucketName) throws CosClientException, CosServiceException {
        // bucket 的命名规则为{name}-{appid} ，此处填写的存储桶名称必须为此格式
        return cosClient.getBucketLocation(bucketName);
    }

}
